﻿using System;
using System.Text;
using System.Windows.Forms;

namespace MyFastDataSourceBind
{
    /// <summary>
    /// 可绑定到数据源的复选框控件
    /// </summary>
    /// <remarks>
    /// 开发人员可以设置本控件的XDataSourceName属性来绑定到指定的数据源上，
    /// 可以设置XDataFieldName属性来绑定到数据源指定的字段上，使得控件能自动
    /// 显示数据源中的数据。
    /// 编制 袁永福</remarks>
    public class XDBCheckBox : System.Windows.Forms.CheckBox, IXDataSourceable
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        public XDBCheckBox()
        {
        }


        private string strXDataFieldName = null;
        /// <summary>
        /// 控件绑定的数据源字段名
        /// </summary>
        [System.ComponentModel.Editor(
            typeof(XDataFieldNameEditor),
            typeof(System.Drawing.Design.UITypeEditor))]
        public string XDataFieldName
        {
            get
            {
                return strXDataFieldName;
            }
            set
            {
                strXDataFieldName = value;
            }
        }

        private string strXDataSourceName = null;
        /// <summary>
        /// 绑定的数据源名称
        /// </summary>
        [System.ComponentModel.Editor(
            typeof(XDataSourceNameEditor),
            typeof(System.Drawing.Design.UITypeEditor))]
        public string XDataSourceName
        {
            get
            {
                return strXDataSourceName;
            }
            set
            {
                strXDataSourceName = value;
                XDataSourceEventSender.Register(this, strXDataSourceName);
            }
        }

        /// <summary>
        /// 销毁对象,取消数据源绑定
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            XDataSourceEventSender.UnRegister(this);
        }

        /// <summary>
        /// 处理数据源事件
        /// </summary>
        /// <param name="Sender">参数</param>
        /// <param name="Args">事件参数</param>
        public void HandleDataSourceEvent(object Sender, XDataSourceEventArgs Args)
        {
            switch (Args.Style)
            {
                case XDataSourceEventStyle.FillUI:
                    // 响应FillUI事件，从数据源读取数据并设置复选框状态
                    object v = Args.DataSource.GetValue(this.XDataFieldName);
                    this.Checked = ValueTypeHelper.GetBoolean(v);
                    this.Enabled = Args.DataSource.CanEdit(this.XDataFieldName);
                    break;
                case XDataSourceEventStyle.ReadUI:
                    // 响应ReadUI事件，根据复选框状态设置数据源数据
                    Args.DataSource.SetValue(this.XDataFieldName, this.Checked);
                    break;
            }
        }
    }//public class XDBCheckBox
}